package com.sibu.yx.promotion.common.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import com.alibaba.fastjson.JSONObject;
import com.doubo.common.util.ExceptionUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 
* @ClassName: HttpsUtil 
* @Description: https请求
* @author xiaoheliu
* @date 2016年5月17日 下午3:32:57 
*
 */
@Slf4j
public class HttpsUtil {

	/**
	 * 发起https请求
	 * @param requestUrl 请求地址
	 * @param requestMethod 请求方式（Get或者post）
	 * @param outputStr 提交数据
	 * @return
	 */
	public static JSONObject httpsRequest(String requestUrl,
										  String requestMethod, String outputStr) {
		JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
		HttpsURLConnection httpsUrlConn = null;
		BufferedReader bufferedReader = null;
		InputStreamReader inputStreamReader = null;
		InputStream inputStream = null;
		try {
			// 创建SSLcontext管理器对像，使用我们指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			SSLSocketFactory ssf = sslContext.getSocketFactory();
			SSLSocket socket = (SSLSocket) ssf.createSocket();
			socket.setEnabledProtocols(new String[]{"SSLv3", "TLSv1"});

			URL url = new URL(requestUrl);
			httpsUrlConn = (HttpsURLConnection) url
					.openConnection();
			httpsUrlConn.setSSLSocketFactory(ssf);
			httpsUrlConn.setDoInput(true);
			httpsUrlConn.setDoOutput(true);
			httpsUrlConn.setUseCaches(false);
			// 设置请求方式（GET/POST）
			httpsUrlConn.setRequestMethod(requestMethod);
			if ("GET".equalsIgnoreCase(requestMethod)) {
				httpsUrlConn.connect();
			}
			// 当有数据需要提交时
			if (outputStr != null) {
				OutputStream outputStream = httpsUrlConn.getOutputStream();
				// 防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
				outputStream = null;
			}

			// 将返回的输入流转换成字符串
			inputStream = httpsUrlConn.getInputStream();
			inputStreamReader = new InputStreamReader(
					inputStream, "UTF-8");
			bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}

			httpsUrlConn.disconnect();
			httpsUrlConn = null;
			jsonObject = JSONObject.parseObject(buffer.toString());
		} catch (ConnectException ce) {
			log.error("https ConnectException, url:[{}], param:[{}]", requestUrl, outputStr);
		} catch (Exception e) {
			log.error("https request Exception, url:[{}], param:[{}]", requestUrl, outputStr);
		} finally {
			try {
				if(null != bufferedReader) {
					bufferedReader.close();
				}
				if(null != inputStreamReader) {
					inputStreamReader.close();
				}
				if (null != inputStream) {
					inputStream.close();
				}
				if (null != httpsUrlConn) {
					httpsUrlConn.disconnect();
				}
			} catch (Exception e) {
				log.error("colse stream Exception:{}", ExceptionUtil.getAsString(e));
			}
		}
		return jsonObject;
	}
	
	
	/**
	 * 发起https请求
	 * @param requestUrl 请求地址
	 * @param requestMethod 请求方式（Get或者post）
	 * @param outputStr 提交数据
	 * @return
	 */
	public static String sendXmlHttps(String requestUrl,
			String requestMethod, String outputStr) {
		StringBuffer buffer = null;
		HttpsURLConnection httpsUrlConn = null;
		BufferedReader bufferedReader = null;
		InputStreamReader inputStreamReader = null;
		InputStream inputStream = null;
		try {
			buffer = new StringBuffer();
			// 创建SSLcontext管理器对像，使用我们指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);
			httpsUrlConn = (HttpsURLConnection) url
					.openConnection();
			httpsUrlConn.setSSLSocketFactory(ssf);
			httpsUrlConn.setDoInput(true);
			httpsUrlConn.setDoOutput(true);
			httpsUrlConn.setUseCaches(false);
			// 设置请求方式（GET/POST）
			httpsUrlConn.setRequestMethod(requestMethod);
			httpsUrlConn.setRequestProperty("content-type", "text/xml; charset=UTF-8");
			if ("GET".equalsIgnoreCase(requestMethod)) {
				httpsUrlConn.connect();
			}
			// 当有数据需要提交时
			if (outputStr != null) {
				OutputStream outputStream = httpsUrlConn.getOutputStream();
				// 防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
				outputStream = null;
			}

			// 将返回的输入流转换成字符串
			inputStream = httpsUrlConn.getInputStream();
			inputStreamReader = new InputStreamReader(
					inputStream, "UTF-8");
			bufferedReader = new BufferedReader(
					inputStreamReader);
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			httpsUrlConn.disconnect();
		} catch (Exception e) {
			log.error("https request Exception, url:[{}], param:[{}], exception:[{}]", requestUrl, outputStr, ExceptionUtil.getAsString(e));
		} finally {
			try {
				if(null != bufferedReader) {
					bufferedReader.close();
				}
				if(null != inputStreamReader) {
					inputStreamReader.close();
				}
				if (null != inputStream) {
					inputStream.close();
				}
				if (null != httpsUrlConn) {
					httpsUrlConn.disconnect();
				}
			} catch (Exception e) {
				log.error("colse stream Exception:{}", ExceptionUtil.getAsString(e));
			}
		}
		return buffer.toString();
	}
}
